/**
 * 
 */
package pt.inescid.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Sergio Esteves (sesteves at gsd.inesc-id.pt)
 *
 */
public class FileUtils {

	public static void generateFile(String location, byte[] src) throws IOException {		
		OutputStream os = new FileOutputStream(new File(location));
		os.write(src);
		os.close();			
	}	

	public static byte[] getDataFromFile(String location) throws IOException {
		File file = new File(location);
		InputStream inputStream = new FileInputStream(file);
		byte[] data = new byte[(int)file.length()];			
		inputStream.read(data);
		inputStream.close();
		return data;
	}
	
	public static long getFileSize(String location) {
		return new File(location).length();
	}
	
	public static void generateTextFile(String location, byte[] src) throws IOException {
		BufferedWriter bw = new BufferedWriter(new FileWriter(location));
		bw.write(new String(src));
		bw.close();		
	}
	
	public static void generateTextFile(String location, String content) {		
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(location));
			bw.write(content);
			bw.close();		
		} catch (IOException e) {
			System.err.println("Error: IOException occurred: " + e.getMessage());
		}		
	}
	
	public static long getDirSize(String location) {
		long size = 0;
		File dir = new File(location);
		for(File f : dir.listFiles())
			size += f.length();
		return size;
	}
	
	public static void copyFile(String source, String destination) {
		try {
			File srcF = new File(source);
			File dstF = new File(destination);

			InputStream in = new FileInputStream(srcF);		
			OutputStream out = new FileOutputStream(dstF);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0){
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch(IOException e) {
			System.err.println("Error: IOException occurred: " + e.getMessage());
		}		
	}
}
